﻿using System;
using System.Globalization;
using System.Text;
using SSG.Model;

namespace SSG.Tools
{
    /// <summary>
    /// Coordinates
    /// </summary>
    public static class Coordinates
    {
        public static readonly CultureInfo ParseCulture = CultureInfo.GetCultureInfo("en-US");

        /// <summary>
        /// To formatted deg/min/sec/ms string
        /// </summary>
        /// <param name="latLngDeg"></param>
        /// <returns></returns>
        public static string LatLngDegToDegMinSecStr(double latLngDeg)
        {
            int d, m, s, ms;
            Fix.LatLngDegToDegMinSec(latLngDeg, true, out d, out m, out s, out ms);
            StringBuilder sb = new StringBuilder(d.ToString(CultureInfo.InvariantCulture).PadLeft(3, '0'));
            sb.Append('.');
            sb.Append(m.ToString(CultureInfo.InvariantCulture).PadLeft(2, '0'));
            sb.Append('.');
            sb.Append(s.ToString(CultureInfo.InvariantCulture).PadLeft(2, '0'));
            sb.Append('.');
            sb.Append(ms.ToString(CultureInfo.InvariantCulture).PadLeft(3, '0'));
            return sb.ToString();
        }

        /// <summary>
        /// String, e.g. 49.30.20.33
        /// </summary>
        /// <param name="latLngStr"></param>
        /// <returns></returns>
        public static double LatLngDegMinSecMsStrToDecimalDeg(string latLngStr)
        {
            if (String.IsNullOrEmpty(latLngStr)) throw new ArgumentNullException("latLngStr");
            string[] parts = latLngStr.Split('.');
            double deg = Math.Abs(Double.Parse(parts[0]));
            double sign = parts[0].StartsWith("-") ? -1.0 : 1.0;
            if (parts.Length > 1) {
                double min = Double.Parse(parts[1]);
                deg += min/60.0;
                if (parts.Length > 2) {
                    string sst = parts.Length > 3 ? parts[2] + "." + parts[3] : parts[2];
                    double sec = Double.Parse(sst, NumberStyles.Float | NumberStyles.AllowThousands, Coordinates.ParseCulture);
                    deg += sec/3600.0;
                }
            }
            return deg*sign;
        }
    }
}